package cn.fintecher.pangolin.service.business.web;

import cn.fintecher.pangolin.common.enums.*;
import cn.fintecher.pangolin.common.exception.BadRequestException;
import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.mysql.CaseInfo;
import cn.fintecher.pangolin.entity.mysql.PaymentCheck;
import cn.fintecher.pangolin.entity.mysql.QPaymentCheck;
import cn.fintecher.pangolin.service.business.model.request.PaymentCheckRequest;
import cn.fintecher.pangolin.service.business.model.request.PaymentReplyRequest;
import cn.fintecher.pangolin.service.business.model.request.ReplyPaymentCheckRequest;
import cn.fintecher.pangolin.service.business.repository.jparepository.CaseInfoRepository;
import cn.fintecher.pangolin.service.business.repository.jparepository.PaymentCheckRepository;
import cn.fintecher.pangolin.service.business.service.BaseService;
import com.querydsl.core.BooleanBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;


@RestController
@RequestMapping("/api/paymentCheckController")
@Api(value = "还款核查", description = "还款核查")
public class PaymentCheckController {

    @Autowired
    private PaymentCheckRepository paymentCheckRepository;

    @Autowired
    private CaseInfoRepository caseInfoRepository;

    @Autowired
    private BaseService baseService;

    @GetMapping("/queryPtpRecord")
    @ApiOperation(value = "ptp 记录查询", notes = "ptp 记录查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", dataType = "int", paramType = "query", value = "页数 (0..N)"),
            @ApiImplicitParam(name = "size", dataType = "int", paramType = "query", value = "每页大小."),
            @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query", value = "依据什么排序: 属性名(,asc|desc). ")
    })
    public ResponseEntity<Page<PaymentCheck>> queryPtpRecord(Pageable pageable, String caseId, @RequestHeader(value = "X-UserToken") String token) {
        baseService.getUserByToken(token);
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(QPaymentCheck.paymentCheck.payCheckStatus.eq(PayCheckStatus.PTP))
                .and(QPaymentCheck.paymentCheck.caseId.eq(caseId));
        Page<PaymentCheck> paymentCheckPage = paymentCheckRepository.findAll(booleanBuilder, pageable);
        return new ResponseEntity<>(paymentCheckPage, HttpStatus.OK);
    }

    @GetMapping("/queryCpRecord")
    @ApiOperation(value = "cp 记录查询", notes = "cp 记录查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", dataType = "int", paramType = "query", value = "页数 (0..N)"),
            @ApiImplicitParam(name = "size", dataType = "int", paramType = "query", value = "每页大小."),
            @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query", value = "依据什么排序: 属性名(,asc|desc). ")
    })
    public ResponseEntity<Page<PaymentCheck>> queryCpRecord(Pageable pageable, String caseId, @RequestHeader(value = "X-UserToken") String token) {
        baseService.getUserByToken(token);
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(QPaymentCheck.paymentCheck.payCheckStatus.eq(PayCheckStatus.CP))
                .and(QPaymentCheck.paymentCheck.caseId.eq(caseId));
        Page<PaymentCheck> paymentCheckPage = paymentCheckRepository.findAll(booleanBuilder, pageable);
        return new ResponseEntity<>(paymentCheckPage, HttpStatus.OK);
    }

    @ApiOperation(value = "跳票", notes = "跳票")
    @PutMapping("/bouncedCheck/{id}/{caseId}/{caseType}")
    public ResponseEntity<Void> bouncedCheck(@PathVariable String id,
                                             @PathVariable String caseId,
                                             @PathVariable CaseType caseType,
                                             @RequestHeader(value = "X-UserToken") String token) {
        Optional<CaseInfo> optional = caseInfoRepository.findById(caseId);
        if (!optional.isPresent()) {
            throw new BadRequestException(null, "caseInfo", "case.is.done");
        }
        CaseInfo caseInfo = optional.get();
        if (!caseType.equals(caseInfo.getCaseType())) {
            throw new BadRequestException(null, "caseInfo", "case.type.is.change");
        }
        if (caseInfo.getCaseDataStatus().equals(CaseDataStatus.PAUSE)) {
            throw new BadRequestException(null, "caseInfo", "case.is.stop");
        }
        if (caseInfo.getCaseDataStatus().equals(CaseDataStatus.SETTLT) || caseInfo.getCaseDataStatus().equals(CaseDataStatus.REDUCE)) {
            throw new BadRequestException(null, "caseInfo", "case.is.clear");
        }
        if (caseInfo.getPublicCaseFlag().equals(PublicCaseFlag.PUBLIC_CASE)) {
            throw new BadRequestException(null, "caseInfo", "case.is.public");
        }
        UserModel userByToken = baseService.getUserByToken(token);
        PaymentCheck paymentCheck = paymentCheckRepository.findById(id).orElseThrow(() -> new BadRequestException(null, null, "data.is.not.exists"));
        paymentCheck.setIsBouncedCheck(BaseSelect.YES);
        paymentCheck.setOperatorDate(ZWDateUtil.getNowDateTime());
        paymentCheck.setOperator(userByToken.getId());
        paymentCheckRepository.save(paymentCheck);
        return ResponseEntity.ok().build();
    }

    @ApiOperation(value = "ptp转cp", notes = "ptp转cp")
    @PostMapping("/changeStatus")
    public ResponseEntity<Void> changeStatus(@RequestBody PaymentCheckRequest paymentCheckRequest, @RequestHeader(value = "X-UserToken") String token) {
        Optional<CaseInfo> optional = caseInfoRepository.findById(paymentCheckRequest.getCaseId());
        if (!optional.isPresent()) {
            throw new BadRequestException(null, "caseInfo", "case.is.done");
        }
        CaseInfo caseInfo = optional.get();
        if (!paymentCheckRequest.getCaseType().equals(caseInfo.getCaseType())) {
            throw new BadRequestException(null, "caseInfo", "case.type.is.change");
        }
        if (caseInfo.getCaseDataStatus().equals(CaseDataStatus.PAUSE)) {
            throw new BadRequestException(null, "caseInfo", "case.is.stop");
        }
        if (caseInfo.getCaseDataStatus().equals(CaseDataStatus.SETTLT) || caseInfo.getCaseDataStatus().equals(CaseDataStatus.REDUCE)) {
            throw new BadRequestException(null, "caseInfo", "case.is.clear");
        }
        if (caseInfo.getPublicCaseFlag().equals(PublicCaseFlag.PUBLIC_CASE)) {
            throw new BadRequestException(null, "caseInfo", "case.is.public");
        }
        UserModel userByToken = baseService.getUserByToken(token);
        PaymentCheck paymentCheck = paymentCheckRepository.findById(paymentCheckRequest.getId()).orElseThrow(() -> new BadRequestException(null, "changeStatus", "data.is.not.exists"));
//        BooleanBuilder booleanBuilder  = new BooleanBuilder();
//        booleanBuilder.and(QPaymentCheck.paymentCheck.caseId.eq(paymentCheckRequest.getCaseId()))
//                .and(QPaymentCheck.paymentCheck.payCheckStatus.eq(PayCheckStatus.CP)
//                .and(QPaymentCheck.paymentCheck.isReply.eq(BaseSelect.NO)));
//        long count = paymentCheckRepository.count(booleanBuilder);
//        if(count > 0){
//            throw  new BadRequestException(null,"changeStatus","cp.is.exists");
//        }
        paymentCheck.setPayCheckStatus(PayCheckStatus.CP);
        paymentCheck.setHasPaymentDate(paymentCheck.getPromiseDate());
        paymentCheck.setHasPaymentAmt(paymentCheck.getPromiseAmt());
        paymentCheck.setReason(paymentCheckRequest.getReason());
        paymentCheck.setApplyName(userByToken.getRealName());
        paymentCheck.setApplyId(userByToken.getId());
        paymentCheck.setApplyDate(ZWDateUtil.getNowDateTime());
        paymentCheck.setOperatorDate(ZWDateUtil.getNowDateTime());
        paymentCheck.setOperator(userByToken.getId());
        paymentCheckRepository.save(paymentCheck);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/queryReplyRecord")
    @ApiOperation(value = "还款核查回复", notes = "还款核查回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", dataType = "int", paramType = "query", value = "页数 (0..N)"),
            @ApiImplicitParam(name = "size", dataType = "int", paramType = "query", value = "每页大小."),
            @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query", value = "依据什么排序: 属性名(,asc|desc). ")
    })
    public ResponseEntity<Page<PaymentCheck>> queryReplyRecord(Pageable pageable, PaymentReplyRequest paymentReplyRequest, @RequestHeader(value = "X-UserToken") String token) {
        UserModel userModel = baseService.getUserByToken(token);
        BooleanBuilder booleanBuilder = paymentReplyRequest.generateBooleanBuilder();
        if (userModel.getIsCheck().equals(BaseSelect.YES)) {
            booleanBuilder.and(QPaymentCheck.paymentCheck.principalId.in(userModel.getPrincipalIds()));
        }
        Page<PaymentCheck> paymentCheckPage = paymentCheckRepository.findAll(booleanBuilder, pageable);
        return new ResponseEntity<>(paymentCheckPage, HttpStatus.OK);
    }

    @ApiOperation(value = "回复cp", notes = "回复cp")
    @PostMapping("/replyPaymentCheck")
    public ResponseEntity<Void> replyPaymentCheck(@RequestBody ReplyPaymentCheckRequest replyPaymentCheckRequest, @RequestHeader(value = "X-UserToken") String token) {
        UserModel userByToken = baseService.getUserByToken(token);
        PaymentCheck paymentCheck = paymentCheckRepository.findById(replyPaymentCheckRequest.getId()).orElseThrow(() -> new BadRequestException(null, "changeStatus", "data.is.not.exists"));
        paymentCheck.setRemark(replyPaymentCheckRequest.getRemark());
        paymentCheck.setReplyName(userByToken.getRealName());
        paymentCheck.setReplyDate(ZWDateUtil.getNowDateTime());
        paymentCheck.setHasPaymentAmt(replyPaymentCheckRequest.getFallBackAmount());
        paymentCheck.setIsReply(BaseSelect.YES);
        paymentCheck.setOperatorDate(ZWDateUtil.getNowDateTime());
        paymentCheck.setOperator(userByToken.getId());
        paymentCheckRepository.save(paymentCheck);
        String content = "客户姓名为:[" + paymentCheck.getPersonalName() + "]的查账回复完成";
        baseService.sendMessageToOne(MessageType.APPLY_APPROVE_MSG, "查账回复", content, paymentCheck.getApplyId());
        return ResponseEntity.ok().build();
    }

}
